package com.design.security.config;

import com.design.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.CorsFilter;

import java.util.List;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private SecurityIgnoreConfig securityIgnoreConfig;

	// 自定义token认证过滤器
	@Autowired
	private JwtAuthenticationTokenFilter authenticationTokenFilter;

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new CustomMd5PasswordEncoder();
	}

	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 取出配置文件中的所有白名单
		List<String> ignoreWhites = securityIgnoreConfig.getWhites();
		http.
				//关闭csrf
						csrf().disable()
				// 不通过session获取SecurityContext
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
				.and()
				.authorizeRequests();
		for (String url : ignoreWhites) {
			http.authorizeRequests().antMatchers(url).permitAll();
		}
		// 除上面外的所有请求全部需要鉴权认证
		http.authorizeRequests().anyRequest().authenticated();
		// 自定义认证过滤器
		http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
	}


}
